package com.niit.Hbase.woedcount;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;

import java.io.IOException;

/**
 * @author:Yan
 * @date: 2022年11月16日 13:13
 * @desc:
 */
/*
keyin :Text
valuein : IntWritable
keyout: ImmutableBytesWritable  行键
 */
public class WordCountReduce extends TableReducer<Text, IntWritable, ImmutableBytesWritable> {


    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        //统计接收数据值
        int sum = 0;

        for (IntWritable i : values){
            //单词出现的次数累加
            sum += i.get();

        }
        //输出：向HBASE中添加一条数据put对象

        Put put = new Put(Bytes.toBytes(key.toString()));//rowkey

        //列值  往HBASE表添加整数时可能出现乱码，
        put.addColumn(Bytes.toBytes("content"),Bytes.toBytes("count"),Bytes.toBytes(String.valueOf(sum)));

        //写入HBASE
        context.write(new ImmutableBytesWritable(Bytes.toBytes(key.toString())) ,put);
    }
}
